﻿using IntelligentGateway.Data;
using IntelligentGateway.Model;
using IntelligentGateway.Tools;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace IntelligentGateway.Services
{
    public class LoginServices
    {
        public UserInfo? LoginProcess(string LoginCode, string Password)
        {
            UserDA userDA = new UserDA();
            string pwdAfter = SecureTools.Encrypt(Password);
            UserInfo? user = userDA.LoginProc(LoginCode, pwdAfter);
            return user;
        }
        public ClaimsPrincipal GetPrincipalFromExpiredToken(string token,JwtSettings jwtSettings)
        {
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = false,
                ValidateIssuerSigningKey = true,
                ValidAudience = jwtSettings.Audience,
                ValidIssuer = jwtSettings.Issuer,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))

            };

            var tokenHandler = new JwtSecurityTokenHandler();
            SecurityToken securityToken;
            var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken);
            var jwtSecurityToken = securityToken as JwtSecurityToken;
            if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
                throw new SecurityTokenException("Invalid token");

            return principal;
        }
        public string MakeToken(UserInfo info, JwtSettings jwtSettings)
        {
            string strToken = "";
            var claim = new Claim[]{
                   new Claim("ID",info.ID.ToString()),
                   new Claim("Name",info.UserName),
                   new Claim("ProjectID",info.ProjectID.ToString())
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken
            (
                issuer: jwtSettings.Issuer,
                audience: jwtSettings.Audience,
                claims: claim,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddHours(10),//过期时间                
                signingCredentials: creds
            );
            try
            {
                strToken = new JwtSecurityTokenHandler().WriteToken(token);
            }
            catch (Exception ee) { return ""; }

            return strToken;
        }
    }
}
